package com.dhcc.controller;

import com.dhcc.api.R;
import com.dhcc.dto.AddSysInstitution;
import com.dhcc.entity.ClientUser;
import com.dhcc.entity.SysInstitution;
import com.dhcc.entity.SysInstitutionRole;
import com.dhcc.httpApiService.IdGeneratorService;
import com.dhcc.service.*;
import com.dhcc.utils.AuthUtil;
import com.dhcc.vo.InstitutionAndAdminVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/userSystem/institution")
public class InstitutionController {
    @Resource
    private SysInstitutionService sysInstitutionService;
    @Resource
    private SysUserDepartmentInstitutionService sysUserDepartmentInstitutionService;
    @Resource
    private ClientUserService clientUserService;
    @Resource
    private IdGeneratorService idGeneratorService;
    @Resource
    private SysInstitutionInstitutionRoleService sysInstitutionInstitutionRoleService;
    @Resource
    private SysInstitutionRoleService sysInstitutionRoleService;
    /**
     * 查询企业信息
     */
    @GetMapping("/selectInstitution")
    public R<SysInstitution> selectInstitution(String institutionId){
        return R.data(sysInstitutionService.selectInstitutionById(institutionId));
    }
    /**
     * 变更企业信息
     */
    /*@PostMapping("/changeInstitution")
    public R changeInstitution(SysInstitution sysInstitution){
        
    }*/
    /**
     * 查询当前机构下的子机构列表
     */
    @GetMapping("/selectChildInstitutionList")
    public R<List<SysInstitution>> selectChildInstitutionList(String institutionId){
        //查询子机构列表
        List<SysInstitution> institutionChildList= sysInstitutionService.selectChildInstitutionList(institutionId);
        return R.data(institutionChildList);
    }
    /**
     * 查询机构详情和机构管理员信息
     */
    @GetMapping("/selectInstitutionAndAdminInfo")
    public R<InstitutionAndAdminVo> selectInstitutionAndAdminInfo(String institutionId){
        InstitutionAndAdminVo institutionAndAdminVo=new InstitutionAndAdminVo();
        //通过机构编号查询机构信息
        SysInstitution sysInstitution = sysInstitutionService.selectInstitutionById(institutionId);
        BeanUtils.copyProperties(sysInstitution,institutionAndAdminVo);
        //查询当前机构角色
        String institutionRoleId = sysInstitutionInstitutionRoleService.getInstitutionRoles(institutionId);
        SysInstitutionRole institutionRole = sysInstitutionRoleService.getInstitutionRole(institutionRoleId);
        institutionAndAdminVo.setInstitutionRoleId(institutionRoleId);
        institutionAndAdminVo.setInstitutionRoleName(institutionRole.getInstitutionRoleName());
        //通过机构编号，机构角色编号,部门编号为空,以及岗位编号为管理员查询对应的用户编号
        String userId= sysUserDepartmentInstitutionService.selectAdminId(institutionId,institutionRoleId);
        //通过用户编号查询用户信息
        ClientUser user = clientUserService.getUserById(userId);
        institutionAndAdminVo.setAdminName(user.getName());
        institutionAndAdminVo.setAdminUserName(user.getUserName());
        institutionAndAdminVo.setAdminPhone(user.getPhone());
        institutionAndAdminVo.setAdminCardType(user.getCardType());
        institutionAndAdminVo.setAdminCardNumber(user.getCardNumber());
        institutionAndAdminVo.setAdminCardFront(user.getCardFront());
        institutionAndAdminVo.setAdminCardBehind(user.getCardBehind());
        return R.data(institutionAndAdminVo);
    }
    /**
     * 新增机构和管理员
     */
    @PostMapping("/addInstitutionAndAdmin")
    @Transactional
    public R addInstitutionAndAdmin(@RequestBody AddSysInstitution addSysInstitution){
        SysInstitution sysInstitution=new SysInstitution();
        BeanUtils.copyProperties(addSysInstitution,sysInstitution);
        Long institutionId = idGeneratorService.nextId();
        sysInstitution.setInstitutionId(institutionId.toString());
        sysInstitution.setStatus(0);
        sysInstitution.setDeleteFlag(0);
        sysInstitution.setCreateUser(clientUserService.getUserById(AuthUtil.getUserId()).getName());
        // 获取当前时间并格式化为 "yyyy-MM-dd HH:mm:ss"
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);

        // 如果需要存储到数据库的字段是 LocalDate，可以只提取日期部分
        LocalDate localDate = now.toLocalDate(); // 或者直接使用 now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) 然后解析为 LocalDate
        sysInstitution.setCreateTime(Date.valueOf(localDate)); // 将 LocalDate 转换为 java.sql.Date

        //添加机构信息
        Integer addInstitutionResult= sysInstitutionService.addInstitution(sysInstitution);
        if (addInstitutionResult!=1){
            throw new RuntimeException("机构表添加数据异常");
        }
        //生成管理员编号
        Long adminId = idGeneratorService.nextId();
        //在用户表添加新的用户信息
        ClientUser clientUser=new ClientUser();
        clientUser.setUserId(String.valueOf(adminId));
        clientUser.setUserName(addSysInstitution.getAdminUserName());
        clientUser.setPhone(addSysInstitution.getAdminPhone());
        clientUser.setCardType(addSysInstitution.getAdminCardType());
        clientUser.setCardNumber(addSysInstitution.getAdminCardNumber());
        clientUser.setCardFront(addSysInstitution.getAdminCardFront());
        clientUser.setCardBehind(addSysInstitution.getAdminCardBehind());
        clientUser.setDelFlag((byte) 0);
        clientUser.setStatus((byte) 0);
        clientUser.setCreateTime(String.valueOf(localDate));
        clientUser.setCreateUser(clientUserService.getUserById(AuthUtil.getUserId()).getName());
        clientUser.setUserPassword("dhcc@1234");
        clientUser.setName(addSysInstitution.getAdminUserName());
        Integer integer = clientUserService.addUser(clientUser);
        if (integer!=1){
            throw new RuntimeException("用户添加失败");
        }
        //添加管理员信息（在机构，用户，部门，岗位关联表中添加数据）
        Integer addResult= sysUserDepartmentInstitutionService.addInstitutionData(adminId.toString(),institutionId.toString(),"5","1",addSysInstitution.getInstitutionRoleId());
        if (addResult!=1){
            throw new RuntimeException("机构，用户，部门，岗位关联表添加数据异常");
        }
        //在机构编号,机构角色关联表中添加数据
        Integer result=sysInstitutionInstitutionRoleService.addData(institutionId.toString(),addSysInstitution.getInstitutionRoleId());
        if (result!=1){
            throw new RuntimeException("机构，机构角色关联表添加数据异常");
        }
        return R.success();
    }
    /**
     * 修改机构信息
     */
    @PostMapping("/updateInstitution")
    public R updateInstitution(@RequestBody AddSysInstitution addSysInstitution){

        SysInstitution sysInstitution=new SysInstitution();
        BeanUtils.copyProperties(addSysInstitution,sysInstitution);
        // 获取当前时间并格式化为 "yyyy-MM-dd HH:mm:ss"
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);

        // 如果需要存储到数据库的字段是 LocalDate，可以只提取日期部分
        LocalDate localDate = now.toLocalDate(); // 或者直接使用 now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) 然后解析为 LocalDate
        sysInstitution.setUpdateTime(Date.valueOf(localDate));
        String userId = AuthUtil.getUserId();
        ClientUser user = clientUserService.getUserById(userId);
        sysInstitution.setUpdateUser(user.getName());
        //通过机构编号修改机构信息
        Integer updateResult= sysInstitutionService.updateInstitution(sysInstitution);
        if (updateResult!=1){
            throw new RuntimeException("机构表数据更新失败");
        }
        return R.success();
    }
    /**
     * 查询所有的机构角色
     */
    @GetMapping("/getAllInstitutionRole")
    public R<List<SysInstitutionRole>> getAllInstitutionRole(){
        List<SysInstitutionRole> sysInstitutionRoleList= sysInstitutionService.getAllInstitutionRole();
        return R.data(sysInstitutionRoleList);
    }
    /**
     * 删除机构信息
     */
    @GetMapping("/deleteInstitution")
    @Transactional
    public R deleteInstitution(String institutionId){
        List<SysInstitution> sysInstitutionList = sysInstitutionService.selectChildInstitutionList(institutionId);
        if (sysInstitutionList.size()!=0){
            return R.fail("当前机构下还有子机构，请删除子机构");
        }
        Integer deleteResult= sysInstitutionService.deleteInstitution(institutionId);
        if (deleteResult!=1){
            throw new RuntimeException("机构表删除失败");
        }
        //删除关联信息
        //删除机构，用户，部门，岗位关联表中数据
        Integer addResult= sysUserDepartmentInstitutionService.deleteInstitutionData(institutionId);
        if (addResult!=1){
            throw new RuntimeException("机构，用户，部门，岗位关联表删除数据异常");
        }
        //在机构编号,机构角色关联表中删除数据
        Integer result=sysInstitutionInstitutionRoleService.deleteData(institutionId);
        if (result!=1){
            throw new RuntimeException("机构，机构角色关联表删除数据异常");
        }
        return R.success();
    }
}
